var resultData;
var privilageMap = new Map();
var idxMap = new Map();
var authtree
    ,table
    ,$;
const storageValue = "orgCateTableWidths";

$(document).ready(function () {
    addEvent(document.getElementById('addBtn'), 'click', addCB);
    addEvent(document.getElementById('recycleBtn'), 'click', recycleCB);
});

layui.config({
    base: '/static/lib/layuiadmin/',
}).extend({
    authtree: 'modules/authtree',
}).use(['table', 'authtree'], function () {
    $ = layui.$;
    table = layui.table;
    authtree = layui.authtree;

    var widths = localStorage[storageValue] ? JSON.parse(localStorage[storageValue]) : [120, 300];

    table.render({
        id: 'sysOrgCateList'
        , elem: '#test'
        , url: '/sys-org-cate/list'
        , method: 'post'
        , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
        , even: true//隔行变色
        , limits: [10, 20, 30, 50, 80, 100]//每页条数的选择项，默认：[10,20,30,50,80,100]。
        , limit: 10//每页显示的条数（默认：10）
        , height: 650
        , request: {}
        , where: {flag: 2, socState: 1}
        , cols: [[
            {field: 'id', width: widths[0], title: 'ID', sort: true, align: 'center'}
            , {field: 'socName', width: widths[1], title: '分类名称', align: 'left'}
            , {title: '操作', toolbar: '#barDemo', align: 'center'}
        ]]
        , page: true
        , done: function (res, curr, count) {
            idxMap.clear();

            resultData = res.data;

            for (var i = 0; i < resultData.length; i++) {
                if (i == 0) {
                    $('.funText').html(`给机构分类：<span style="color: #F72E29">${resultData[i].socName}</span>授权以下功能`);
                    load_function_tree(resultData[i].id);
                }

                idxMap.set(resultData[i].id, i);
            }
        }
    });


    //监听行单击事件（单击事件为：rowDouble）
    table.on('row(test)', function (obj) {
        $('.funText').html(`给机构分类：<span style="color: #F72E29">${obj.data.socName}</span>授权以下功能`);
        load_function_tree(obj.data.id);
    });

    //监听行工具事件
    table.on('tool(test)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                $.ajax({
                    async: false,
                    type: 'post',
                    dataType: "json",
                    url: '/sys-org-cate/delete',
                    data: obj.data,
                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                    timeout: 30000,//超时时间设置为1分钟；
                    success: function (data) {
                        if (data.code == 0) {
                            obj.del();
                            layer.close(index);

                            reload();
                        } else {
                            layer.alert(data.msg, {title: '错误信息：'});
                        }
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                    },
                    error: function (a, b, c) {
                        // 请求出错处理,依然初始化咨询节点信息
                        if (b == 'timeout') {
                            layer.alert("请求超时，请再次尝试！", {title: '错误信息：'});
                        } else {
                            layer.alert(url + "请求异常", {title: '错误信息：'});
                        }
                    }
                });
            });
        } else if (obj.event === 'edit') {
            editData(obj.data);
        } else if (obj.event === 'up') {
            moveUp(obj.data);
        } else if (obj.event === 'down') {
            moveDown(obj.data);
        }
    });

    $('th').mouseup(function () {
        var tr = $(this).parent()["0"];
        var widths = [];
        for (var i = 0; i < tr.cells.length - 1; i++) {
            widths.push(tr.cells[i].clientWidth);
        }

        localStorage[storageValue] = JSON.stringify(widths);
    });
});

function reload() {
    table.reload('sysOrgCateList', {
        url: '/sys-org-cate/list'//数据地址
        , where: {} //设定异步数据接口的额外参数
        , page: {
            curr: 1//$('input.layui-input').val()
        }//重新从第 1 页开始
    });
}

function addCB() {
    layer.open({
        type: 2,
        title: "添加分类",
        shadeClose: true,
        area: ['450px', '300px'],
        content: "sysOrgCateDetail.html?type=new",
        end: function () {
            reload();
        }
    });
}

function recycleCB() {
    layer.open({
        type: 2,
        title: "机构分类回收站",
        shadeClose: true,
        area: ['750px', '530px'],
        content: "cateRecycle.html",
        end: function () {
            reload();
        }
    });
}

function editData(data) {
    localStorage.sysOrgCate = JSON.stringify(data);

    layer.open({
        type: 2,
        title: "修改分类",
        shadeClose: true,
        area: ['450px', '300px'],
        content: "sysOrgCateDetail.html?type=edit",
        end: function () {
            reload();
        }
    });
}

/**
 * @author wh
 * @description 上移
 */
function moveUp(data) {
    var idx = idxMap.get(data.id);

    if (idx == 0) {
        layer.msg("已经移动到最顶端！", {icon: 5, time: 2000});
    } else {
        upload(data, idx, true);
    }
}

/**
 * @author wh
 * @description 下移
 */
function moveDown(data) {
    var idx = idxMap.get(data.id);

    if (idx == resultData.length - 1) {
        layer.msg("已经移动到最下端！", {icon: 5, time: 2000});
    } else {
        upload(data, idx, false);
    }
}

/*
* 向服务器提交交换之后的数组
* */
function upload(data, idx, flag) {
    var sort = resultData[idx].socSort;
    var targetIndex = flag ? idx - 1 : idx + 1;

    var datas = [];
    resultData[idx].socSort = resultData[targetIndex].socSort;
    datas.push(resultData[idx]);
    resultData[targetIndex].socSort = sort;
    datas.push(resultData[targetIndex]);

    $.ajax({
            url: '/sys-org-cate/move'
            , data: {cateList: JSON.stringify(datas)}
            , type: 'post'
            , success: function (res) {
                layer.msg("移动成功！", {icon: 1, time: 2000});
                reload();
            }
            , error: function (res) {
                layer.msg(res.msg, {icon: 5, time: 2000});
            }
        }
    );
}

/*
* @author: wj
* @description: 加载授权功能
* @date: 2019/1/17 16:25
* @param
* @return
*/
function load_function_tree(orgCateId) {
    // 取得岗位授权
    ActHttpRequest('/sys-org-cate-privilege/getPrivilege', {'orgCateId': orgCateId}, function (returnData) {
        if (returnData.code === 0) {
            // 全局变量赋值
            privilageMap.clear();

            if (returnData.List.length > 0) {
                for (var i = 0; i < returnData.List.length; i++) {
                    privilageMap.set(returnData.List[i].functionId, returnData.List[i]);
                }
            }

            var values = formatFunctionData(returnData, "parentId", "functionId", "name", "choiceFlag");
            authtree.render('#functionTree', values, {
                inputname: 'authids[]'
                , layfilter: 'lay-check-auth2'
                , autowidth: true
                , autochecked: false
                , autoclose: false
            });
        }
    });

    authtree.on('change(lay-check-auth2)', function (data) {
        var lastChecked = authtree.getLastChecked('#functionTree') //获取最新选中
            , lastNotChecked = authtree.getLastNotChecked('#functionTree') // 获取最新取消
            , value // 保存值的变量
            , url  // 请求URL
            , parents // 保存父值的变量
            , values; //关联实体一览

        if (lastChecked.length > 0) {
            value = parseInt(lastChecked["0"]);
            parents = getParents([value]);
            url = "/sys-org-cate-privilege/savePrivilege";
        } else {
            value = parseInt(lastNotChecked["0"]);
            url = "/sys-org-cate-privilege/deletePrivilege";
        }

        // 取得关联子项目编号一栏，并取得实体
        var relationIds = getChilds([value]);
        if (parents && parents.length > 0) {
            relationIds = relationIds.concat(parents);
        }
        relationIds.push(value);
        values = [];
        for (var i = 0; i < relationIds.length; i++) {
            var tmpPrivilege = privilageMap.get(relationIds[i]);
            tmpPrivilege.orgCateId = orgCateId;
            values.push(privilageMap.get(relationIds[i]));
        }

        // 向服务器发出Ajax请求
        $.ajax({
            async: false,
            type: 'post',
            dataType: "json",
            url: url,
            data: {"privilageList": JSON.stringify(values)},
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            timeout: 30000,//超时时间设置为1分钟；
            success: function (data) {
                if (data.code == 0) {
                    layer.msg("提交成功!", {icon: 1, time: 1000});
                } else {
                    layer.msg(data.msg, {icon: 1, time: 1000});
                }
            },
            complete: function (XMLHttpRequest, textStatus) {
                load_function_tree(orgCateId);
            },
            error: function (a, b, c) {
                // 请求出错处理,依然初始化咨询节点信息
                if (b == 'timeout') {
                    layer.alert("请求超时，请再次尝试！", {title: '错误信息：'});
                } else {
                    layer.alert(url + "请求异常", {title: '错误信息：'});
                }
            }
        });
    });
}

/**
 * 数据封装
 * @param data 数据
 * @param pid  父ID
 * @param id  ID
 * @param name 显示名称
 * @param checked 选中状态
 */
function formatFunctionData(values, pid, id, name, checked) {
    var tree = [],
        item;

    var map = new Map();

    // 1)变格式保存到Map
    for (var i = 0; i < values.List.length; i++) {
        item = new Object();

        item.name = values.List[i][name];
        item.value = values.List[i][id];
        item.checked = values.List[i][checked];
        item.list = [];

        map.set(values.List[i][id], item);
    }

    // 2)作为子项目加到父项目的list
    for (var i = 0; i < values.List.length; i++) {
        if (values.List[i][pid] > 0) {
            var obj = map.get(values.List[i][pid]);
            obj.list.push(map.get(values.List[i][id]));
        } else {
            tree.push(map.get(values.List[i][id]));
        }
    }

    // 3)删除没有子项目的list
    for (var i = 0; i < values.List.length; i++) {
        var obj = map.get(values.List[i][id]);
        if (obj.list.length == 0) {
            delete obj.list;
        }
    }

    return tree;
}

/**
 * 取得授权功能子节点Id一览
 */
function getChilds(ids) {
    var result = [];

    for (value of privilageMap) {
        if (ids.indexOf(value[1].parentId) >= 0) {
            result.push(value[1].functionId);
        }
    }

    if (result.length > 0) {
        result = result.concat(getChilds(result));
    }

    return result;
}

/**
 * 取得授权功能父节点Id一览
 */
function getParents(ids) {
    var result = [];

    var obj = privilageMap.get(ids[ids.length - 1]);
    var parent;

    // 查找上一个父节点，若没选中的状态则加到result
    if (obj.parentId > 0) {
        parent = privilageMap.get(obj.parentId);
        if (!parent.choiceFlag) {
            result.push(obj.parentId);
            result = result.concat(getParents(result));
        }
    }

    return result;
}